// 表头配置
const TABLE_HEADERS = {
    all: ['订单号', '订单类型', '订单详情', '价格', '状态', '操作'],
    hotel: ['订单号', '房间数', '联系人', '联系电话', '身份证', '价格', '状态', '酒店品牌', '操作'],
    scenic: ['订单号', '景点名称', '景点地址', '价格', '所在城市', '状态', '操作'],
    ticket: ['订单号', '类型', '票型', '出发城市', '到达城市', '出发时间', '价格', '状态', '操作']
};

// 工具函数
function formatPrice(value) {
    if (!value) return '0.00';
    return Number(value).toFixed(2);
}

function mapOrderStatus(status) {
    const statusMap = {
        '待支付': '已完成',
        'null': '已完成',
        'NULL': '已完成',
        undefined: '已完成',
        '已支付': '已完成',
        '已完成': '已完成',
        '已取消': '已取消'
    };
    return statusMap[status] || status || '已完成';
}

function getStatusClass(status) {
    const statusClasses = {
        '待付款': 'text-warning',
        '已付款': 'text-success',
        '已完成': 'text-success',
        '已取消': 'text-danger'
    };
    return statusClasses[status] || '';
}

// 创建表头
function createTableHeader(type) {
    const headers = TABLE_HEADERS[type] || TABLE_HEADERS.all;
    return '<tr>' + headers.map(header => '<th>' + header + '</th>').join('') + '</tr>';
}

// 处理订单数据
function processOrderData(order, type) {
    switch (type) {
        case 'hotel':
            return processHotelOrder({
                ...order.hotel,
                // 添加订单类型前缀到 ID
                id: 'H' + order.hotel.id
            });
        case 'scenic':
            return processScenicOrder({
                ...order.scenicSpot,
                // 添加订单类型前缀到 ID
                id: 'S' + order.scenicSpot.id
            });
        case 'ticket':
            return processTicketOrder({
                ...order.tickets,
                // 添加订单类型前缀到 ID
                id: 'T' + order.tickets.id
            });
        default:
            if (order.hotel) return processHotelOrder({...order.hotel, id: 'H' + order.hotel.id});
            if (order.scenicSpot) return processScenicOrder({...order.scenicSpot, id: 'S' + order.scenicSpot.id});
            if (order.tickets) return processTicketOrder({...order.tickets, id: 'T' + order.tickets.id});
            return null;
    }
}

function processHotelOrder(hotel) {
    if (!hotel) return null;
    return {
        id: hotel.id || '',
        type: '酒店订单',
        details: [
            '房间数: ' + (hotel.roomNum || ''),
            '联系人: ' + (hotel.contactName || ''),
            '电话: ' + (hotel.contactPhone || ''),
            '身份证: ' + (hotel.idCard || ''),
            '品牌: ' + (hotel.brand || '')
        ].join('<br>'),
        price: formatPrice(hotel.price),
        status: mapOrderStatus(hotel.status),
        extraData: {
            roomNum: hotel.roomNum || '',
            contactName: hotel.contactName || '',
            contactPhone: hotel.contactPhone || '',
            idCard: hotel.idCard || '',
            brand: hotel.brand || ''
        }
    };
}

function processScenicOrder(scenic) {
    if (!scenic) return null;
    return {
        id: scenic.id || '',
        type: '景点订单',
        details: [
            '景点名称: ' + (scenic.scenicName || ''),
            '地址: ' + (scenic.scenicAddress || ''),
            '城市: ' + (scenic.city || '')
        ].join('<br>'),
        price: formatPrice(scenic.price),
        status: mapOrderStatus(scenic.status),
        extraData: {
            scenicName: scenic.scenicName || '',
            scenicAddress: scenic.scenicAddress || '',
            city: scenic.city || ''
        }
    };
}

function processTicketOrder(ticket) {
    if (!ticket) return null;
    return {
        id: ticket.id || '',
        type: '车票订单',
        details: [
            '类型: ' + (ticket.type || ''),
            '票型: ' + (ticket.ticketType || ''),
            '出发城市: ' + (ticket.departure_city || ''),
            '到达城市: ' + (ticket.arrival_city || ''),
            '出发时间: ' + (ticket.departure_time || '')
        ].join('<br>'),
        price: formatPrice(ticket.price),
        status: mapOrderStatus(ticket.status),
        extraData: {
            type: ticket.type || '',
            ticketType: ticket.ticketType || '',
            departureCity: ticket.departure_city || '',
            arrivalCity: ticket.arrival_city || '',
            departureTime: ticket.departure_time || ''
        }
    };
}

// 创建操作按钮
function createOperationButtons(orderId, orderType) {

    if (!orderId || !orderType) {
        console.log('创建按钮失败 - 无效参数:', {orderId, orderType});
        return '';
    }

    // 从订单ID中提取实际类型（H/S/T）
    const idPrefix = orderId.charAt(0);
    let actualType = orderType;

    // 根据ID前缀确定实际类型
    if (idPrefix === 'H') actualType = 'hotel';
    else if (idPrefix === 'S') actualType = 'scenic';
    else if (idPrefix === 'T') actualType = 'ticket';

    return `
        <div class="btn-group" role="group">
            <button type="button" class="btn btn-primary btn-sm edit-order-btn" 
                    data-id="${orderId}" 
                    data-type="${actualType}">
                修改
            </button>
            <button type="button" class="btn btn-danger btn-sm delete-order-btn" 
                    data-id="${orderId}" 
                    data-type="${actualType}">
                删除
            </button>
        </div>
    `;
}

// 创建订单行
function createOrderRow(order, type) {
    const data = processOrderData(order, type);
    if (!data) return '';


    let cells = [];
    // 修改订单类型的处理逻辑
    let orderType;
    if (type === 'all') {
        // 从订单类型中提取实际类型
        if (data.type.includes('酒店')) orderType = 'hotel';
        else if (data.type.includes('景点')) orderType = 'scenic';
        else if (data.type.includes('车票')) orderType = 'ticket';
        else orderType = type;
    } else {
        orderType = type; // 使用传入的类型
    }

    const orderId = data.id ? data.id.toString() : '';

    // 创建按钮组
    const buttonGroup = $('<div/>', {
        class: 'btn-group',
        role: 'group'
    });

    // 创建编辑按钮
    $('<button/>', {
        type: 'button',
        class: 'btn btn-primary btn-sm edit-order-btn',
        text: '修改'
    })
        .attr('data-id', orderId)
        .attr('data-type', orderType)
        .appendTo(buttonGroup);

    // 创建删除按钮
    $('<button/>', {
        type: 'button',
        class: 'btn btn-danger btn-sm delete-order-btn',
        text: '删除'
    })
        .attr('data-id', orderId)
        .attr('data-type', orderType)
        .appendTo(buttonGroup);

    // 根据类型创建不同的单元格内容
    switch (type) {
        case 'hotel':
            cells = [
                orderId,
                data.extraData.roomNum || '',
                data.extraData.contactName || '',
                data.extraData.contactPhone || '',
                data.extraData.idCard || '',
                '￥' + (data.price || '0.00'),
                '<span class="' + getStatusClass(data.status) + '">' + (data.status || '') + '</span>',
                data.extraData.brand || '',
                buttonGroup.prop('outerHTML')
            ];
            break;
        case 'scenic':
            cells = [
                orderId,
                data.extraData.scenicName || '',
                data.extraData.scenicAddress || '',
                '￥' + (data.price || '0.00'),
                data.extraData.city || '',
                '<span class="' + getStatusClass(data.status) + '">' + (data.status || '') + '</span>',
                buttonGroup.prop('outerHTML')
            ];
            break;
        case 'ticket':
            cells = [
                orderId,
                data.extraData.type || '',
                data.extraData.ticketType || '',
                data.extraData.departureCity || '',
                data.extraData.arrivalCity || '',
                data.extraData.departureTime || '',
                '￥' + (data.price || '0.00'),
                '<span class="' + getStatusClass(data.status) + '">' + (data.status || '') + '</span>',
                buttonGroup.prop('outerHTML')
            ];
            break;
        default:
            cells = [
                orderId,
                data.type || '',
                data.details || '',
                '￥' + (data.price || '0.00'),
                '<span class="' + getStatusClass(data.status) + '">' + (data.status || '') + '</span>',
                buttonGroup.prop('outerHTML')
            ];
    }

    return '<tr>' + cells.map(cell => '<td>' + cell + '</td>').join('') + '</tr>';
}

// 加载订单数据
function loadOrders(type) {
    const tableBody = $('#orderTableBody');
    tableBody.html('<tr><td colspan="9" class="text-center">加载中...</td></tr>');

    $.ajax({
        url: 'orders',
        type: 'POST',
        data: {action: type + 'Orders'},
        dataType: 'json',
        success: function (response) {
            if (response.success && response.data) {
                renderOrders(response.data, type);
            } else {
                tableBody.html('<tr><td colspan="9" class="text-center text-danger">暂无订单数据</td></tr>');
            }
        }
    });
}

// 渲染订单数据
function renderOrders(orders, type) {
    const tableBody = $('#orderTableBody');
    if (!orders || orders.length === 0) {
        tableBody.html('<tr><td colspan="9" class="text-center">暂无订单数据</td></tr>');
        return;
    }

    const html = orders.map(order => createOrderRow(order, type)).join('');
    tableBody.html(html);
}

// 获取当前订单数据
function getCurrentOrderData(orderId, orderType) {

    // 在全部订单视图中，需要先确定具体的订单类型
    if (orderType === 'all') {
        const row = $(`#orderTableBody tr`).filter(function () {
            return $(this).find('td:first').text().trim() === orderId.toString();
        }).first();

        // 从第二列获取订单类型
        const typeText = row.find('td').eq(1).text().trim();
        // 根据类型文本确定实际类型
        if (typeText.includes('酒店')) {
            orderType = 'hotel';
        } else if (typeText.includes('景点')) {
            orderType = 'scenic';
        } else if (typeText.includes('车票')) {
            orderType = 'ticket';
        }
    }

    // 构建查询选择器，包含订单类型
    const row = $(`#orderTableBody tr`).filter(function () {
        const rowId = $(this).find('td:first').text().trim();
        // 检查订单ID和类型是否匹配
        return rowId === orderId.toString();
    }).first();

    if (row.length === 0) {
        return null;
    }

    const cells = row.find('td');
    const data = {
        id: orderId,
        type: orderType,
        extraData: {}
    };

    // 根据不同类型解析数据
    switch (orderType) {
        case 'hotel':
            // 从详情列解析数据
            if ($('.order-tabs .tab-btn.active').data('type') === 'all') {
                const details = cells.eq(2).html().split('<br>');
                data.extraData = {
                    roomNum: details[0].split(': ')[1] || '',
                    contactName: details[1].split(': ')[1] || '',
                    contactPhone: details[2].split(': ')[1] || '',
                    idCard: details[3].split(': ')[1] || '',
                    brand: details[4].split(': ')[1] || '',
                    price: cells.eq(3).text().replace(/[^0-9.]/g, '')
                };
            } else {
                data.extraData = {
                    roomNum: cells.eq(1).text().trim(),
                    contactName: cells.eq(2).text().trim(),
                    contactPhone: cells.eq(3).text().trim(),
                    idCard: cells.eq(4).text().trim(),
                    price: cells.eq(5).text().replace(/[^0-9.]/g, ''),
                    brand: cells.eq(7).text().trim()
                };
            }
            break;

        case 'scenic':
            if ($('.order-tabs .tab-btn.active').data('type') === 'all') {
                const details = cells.eq(2).html().split('<br>');
                data.extraData = {
                    scenicName: details[0].split(': ')[1] || '',
                    scenicAddress: details[1].split(': ')[1] || '',
                    city: details[2].split(': ')[1] || '',
                    price: cells.eq(3).text().replace(/[^0-9.]/g, '')
                };
            } else {
                data.extraData = {
                    scenicName: cells.eq(1).text().trim(),
                    scenicAddress: cells.eq(2).text().trim(),
                    price: cells.eq(3).text().replace(/[^0-9.]/g, ''),
                    city: cells.eq(4).text().trim()
                };
            }
            break;

        case 'ticket':
            if ($('.order-tabs .tab-btn.active').data('type') === 'all') {
                const details = cells.eq(2).html().split('<br>');
                data.extraData = {
                    type: details[0].split(': ')[1] || '',
                    ticketType: details[1].split(': ')[1] || '',
                    departureCity: details[2].split(': ')[1] || '',
                    arrivalCity: details[3].split(': ')[1] || '',
                    departureTime: details[4].split(': ')[1] || '',
                    price: cells.eq(3).text().replace(/[^0-9.]/g, '')
                };
            } else {
                data.extraData = {
                    type: cells.eq(1).text().trim(),
                    ticketType: cells.eq(2).text().trim(),
                    departureCity: cells.eq(3).text().trim(),
                    arrivalCity: cells.eq(4).text().trim(),
                    departureTime: cells.eq(5).text().trim(),
                    price: cells.eq(6).text().replace(/[^0-9.]/g, '')
                };
            }
            break;
    }

    return data;
}

// 创建编辑表单内容
function createEditFormContent(orderType, currentOrder) {

    // 确保 extraData 存在且是对象
    const data = currentOrder?.extraData || {};

    // 修改 getFieldValue 函数的处理逻辑
    const getFieldValue = (value) => {
        if (value === 0) return "0";
        if (value === "") return "";
        return value || '';
    };

    // HTML 转义函数
    const escapeHtml = (str) => {
        return String(str)
            .replace(/&/g, '&amp;')
            .replace(/</g, '&lt;')
            .replace(/>/g, '&gt;')
            .replace(/"/g, '&quot;')
            .replace(/'/g, '&#39;');
    };

    // 获取安全的字段值
    const getSafeValue = (field) => escapeHtml(getFieldValue(data[field]));

    // 根据订单类型创建表单
    let formContent = '';
    switch (orderType) {
        case 'hotel':
            formContent = ''
                + '<div class="form-group">'
                + '<label for="roomNum">房间数</label>'
                + '<input type="number" class="form-control" id="roomNum" name="roomNum" value="'
                + getSafeValue('roomNum') + '" required>'
                + '</div>'
                + '<div class="form-group">'
                + '<label for="contactName">联系人</label>'
                + '<input type="text" class="form-control" id="contactName" name="contactName" value="'
                + getSafeValue('contactName') + '" required>'
                + '</div>'
                + '<div class="form-group">'
                + '<label for="contactPhone">联系电话</label>'
                + '<input type="text" class="form-control" id="contactPhone" name="contactPhone" value="'
                + getSafeValue('contactPhone') + '" required>'
                + '</div>'
                + '<div class="form-group">'
                + '<label for="idCard">身份证号</label>'
                + '<input type="text" class="form-control" id="idCard" name="idCard" value="'
                + getSafeValue('idCard') + '" required>'
                + '</div>'
                + '<div class="form-group">'
                + '<label for="price">价格</label>'
                + '<input type="number" class="form-control" id="price" name="price" step="0.01" value="'
                + getSafeValue('price') + '" required>'
                + '</div>'
                + '<div class="form-group">'
                + '<label for="brand">酒店品牌</label>'
                + '<input type="text" class="form-control" id="brand" name="brand" value="'
                + getSafeValue('brand') + '" required>'
                + '</div>';
            break;

        case 'scenic':
            formContent = ''
                + '<div class="form-group">'
                + '<label for="scenicName">景点名称</label>'
                + '<input type="text" class="form-control" id="scenicName" name="scenicName" value="'
                + getSafeValue('scenicName') + '" required>'
                + '</div>'
                + '<div class="form-group">'
                + '<label for="scenicAddress">景点地址</label>'
                + '<input type="text" class="form-control" id="scenicAddress" name="scenicAddress" value="'
                + getSafeValue('scenicAddress') + '" required>'
                + '</div>'
                + '<div class="form-group">'
                + '<label for="price">价格</label>'
                + '<input type="number" class="form-control" id="price" name="price" step="0.01" value="'
                + getSafeValue('price') + '" required>'
                + '</div>'
                + '<div class="form-group">'
                + '<label for="city">所在城市</label>'
                + '<input type="text" class="form-control" id="city" name="city" value="'
                + getSafeValue('city') + '" required>'
                + '</div>';
            break;

        case 'ticket':
            formContent = ''
                + '<div class="form-group">'
                + '<label for="type">类型</label>'
                + '<input type="text" class="form-control" id="type" name="type" value="'
                + getSafeValue('type') + '" required>'
                + '</div>'
                + '<div class="form-group">'
                + '<label for="ticketType">票型</label>'
                + '<input type="text" class="form-control" id="ticketType" name="ticketType" value="'
                + getSafeValue('ticketType') + '" required>'
                + '</div>'
                + '<div class="form-group">'
                + '<label for="departureCity">出发城市</label>'
                + '<input type="text" class="form-control" id="departureCity" name="departureCity" value="'
                + getSafeValue('departureCity') + '" required>'
                + '</div>'
                + '<div class="form-group">'
                + '<label for="arrivalCity">到达城市</label>'
                + '<input type="text" class="form-control" id="arrivalCity" name="arrivalCity" value="'
                + getSafeValue('arrivalCity') + '" required>'
                + '</div>'
                + '<div class="form-group">'
                + '<label for="departureTime">出发时间</label>'
                + '<input type="text" class="form-control" id="departureTime" name="departureTime" value="'
                + getSafeValue('departureTime') + '" required>'
                + '</div>'
                + '<div class="form-group">'
                + '<label for="price">价格</label>'
                + '<input type="number" class="form-control" id="price" name="price" step="0.01" value="'
                + getSafeValue('price') + '" required>'
                + '</div>';
            break;

        default:
            formContent = '<div class="alert alert-danger">未知的订单类型</div>';
    }

    return formContent;
}

// 显示编辑模态框
function showEditModal(orderId, orderType, formContent) {
    // 先移除可能存在的旧模态框
    $('#editOrderModal').remove();

    // 创建新的模态框 HTML
    const modalHtml = ''
        + '<div class="modal" id="editOrderModal" tabindex="-1" role="dialog">'
        + '<div class="modal-dialog" role="document">'
        + '<div class="modal-content">'
        + '<div class="modal-header">'
        + '<h5 class="modal-title">修改订单</h5>'
        + '<button type="button" class="close" data-dismiss="modal" aria-label="Close">'
        + '<span aria-hidden="true">&times;</span>'
        + '</button>'
        + '</div>'
        + '<div class="modal-body">'
        + '<form id="editOrderForm">'
        + '<input type="hidden" name="orderId" value="' + orderId + '">'
        + '<input type="hidden" name="orderType" value="' + orderType + '">'
        + formContent
        + '</form>'
        + '</div>'
        + '<div class="modal-footer">'
        + '<button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>'
        + '<button type="button" class="btn btn-primary" onclick="saveOrderChanges()">保存</button>'
        + '</div>'
        + '</div>'
        + '</div>'
        + '</div>';

    // 添加模态框到 body
    $('body').append(modalHtml);


    // 显示模态框
    $('#editOrderModal').modal({
        backdrop: 'static',
        keyboard: false,
        show: true
    });
}

// 删除订单
function deleteOrder(orderId, orderType) {

    if (!orderId || !orderType) {
        console.log('删除失败 - 参数无效:', {orderId, orderType});
        alert('无效的订单信息');
        return;
    }

    // 从订单ID中提取数字ID
    const numericId = orderId.substring(1);

    // 转换订单类型为后端期望的格式
    const orderTypeMap = {
        'hotel': '酒店',
        'scenic': '景点',
        'ticket': '车票'
    };

    const typeForBackend = orderTypeMap[orderType] || orderType;

    if (!confirm(`确定要删除这个${typeForBackend}订单吗？`)) {
        return;
    }

    $.ajax({
        url: 'deleteOrder',
        type: 'POST',
        data: {
            orderId: numericId, // 使用提取出的数字ID
            orderType: typeForBackend
        },
        success: function (response) {
            const result = typeof response === 'string' ? JSON.parse(response) : response;
            if (result.success) {
                alert('删除成功');
                loadOrders($('.order-tabs .tab-btn.active').data('type'));
            } else {
                alert('删除失败：' + (result.message || '未知错误'));
            }
        }
    });
}

// 保存订单修改
function saveOrderChanges() {
    const form = $('#editOrderForm');
    if (!form[0].checkValidity()) {
        form[0].reportValidity();
        return;
    }

    const formData = new FormData(form[0]);
    const orderType = formData.get('orderType');
    const requestData = {
        orderId: formData.get('orderId'),
        orderType: orderType
    };

    // 根据订单类型添加相应的字段
    switch (orderType) {
        case 'hotel':
            requestData.roomNum = formData.get('roomNum');
            requestData.contactName = formData.get('contactName');
            requestData.contactPhone = formData.get('contactPhone');
            requestData.idCard = formData.get('idCard');
            requestData.price = formData.get('price');
            requestData.brand = formData.get('brand');
            break;
        case 'scenic':
            requestData.scenicName = formData.get('scenicName');
            requestData.scenicAddress = formData.get('scenicAddress');
            requestData.price = formData.get('price');
            requestData.city = formData.get('city');
            break;
        case 'ticket':
            requestData.type = formData.get('type');
            requestData.ticketType = formData.get('ticketType');
            requestData.departureCity = formData.get('departureCity');
            requestData.arrivalCity = formData.get('arrivalCity');
            requestData.departureTime = formData.get('departureTime');
            requestData.price = formData.get('price');
            break;
    }

    $.ajax({
        url: 'updateOrder',
        type: 'POST',
        data: requestData,
        success: function (response) {
            const result = typeof response === 'string' ? JSON.parse(response) : response;
            if (result.success) {
                alert('修改成功');
                $('#editOrderModal').modal('hide');
                loadOrders($('.order-tabs .tab-btn.active').data('type'));
            } else {
                alert('修改失败：' + (result.message || '未知错误'));
            }
        }
    });
}

// 初始化订单管理
function initializeOrderManagement() {

    const tableHeader = createTableHeader('all');
    $('.order-content table thead').html(tableHeader);

    // 绑定标签切换事件
    $('.order-tabs .tab-btn').off('click').on('click', function () {
        const type = $(this).data('type');

        $('.order-tabs .tab-btn').removeClass('active');
        $(this).addClass('active');

        const newHeader = createTableHeader(type);
        $('.order-content table thead').html(newHeader);
        loadOrders(type);
    });

    // 直接使用onclick属性，不再需要事件委托
    loadOrders('all');
}

// 页面加载完成后初始化
$(document).ready(function () {
    if ($('#orderManagementContent').length) {
        initializeOrderManagement();
    }

    // 修改编辑按钮点击事件
    $(document).on('click', '.edit-order-btn', function (e) {
        e.preventDefault();
        const orderId = $(this).data('id');
        const orderType = $(this).data('type');

        console.log('编辑按钮点击:', {orderId, orderType});

        // 获取当前订单数据
        const currentOrder = getCurrentOrderData(orderId, orderType);
        if (!currentOrder) {
            console.log('获取订单数据失败:', {orderId, orderType});
            alert('获取订单数据失败');
            return;
        }

        // 创建表单内容
        const formContent = createEditFormContent(orderType, currentOrder);
        showEditModal(orderId, orderType, formContent);
    });

    // 修改删除按钮点击事件
    $(document).on('click', '.delete-order-btn', function (e) {
        e.preventDefault();
        const orderId = $(this).data('id');
        const orderType = $(this).data('type');

        console.log('删除按钮点击:', {orderId, orderType});

        if (!orderId || !orderType) {
            console.log('无效的订单信息:', {orderId, orderType});
            alert('无效的订单信息');
            return;
        }

        deleteOrder(orderId, orderType);
    });
});

// 导出全局函数
window.initializeOrderManagement = initializeOrderManagement;
window.editOrder = getCurrentOrderData;
window.deleteOrder = deleteOrder;
window.saveOrderChanges = saveOrderChanges;